from flask import Blueprint, request
from flask_cors import CORS
from services.kr36 import get_kr36_hotspot_from_db, get_kr36_hotspot_from_db_page
from blueprints.utils import response_error, response_success, is_page_out_of_bounds

kr36_bp = Blueprint("kr36", __name__, url_prefix="/kr36")

# 定义路由和section的映射关系
SECTION_MAP = {
    "flash": "快讯",
    "latest": "最新资讯",
    "zonghe": "综合榜",
    "hot": "人气榜",
    "bookmark": "收藏榜"
}

CORS(
    kr36_bp, resources={r"/*": {"origins": "http://localhost:5173", "methods": ["GET"], "supports_credentials": True}}
)

@kr36_bp.route("/<section>", methods=["GET"])
def get_kr36_hotspot(section):
    """
    获取36氪数据

    测试地址：
    - http://127.0.0.1:5000/kr36/flash (快讯)
    - http://127.0.0.1:5000/kr36/latest (最新资讯)
    - http://127.0.0.1:5000/kr36/zonghe (综合榜)
    - http://127.0.0.1:5000/kr36/hot (人气榜)
    - http://127.0.0.1:5000/kr36/bookmark (收藏榜)
    """
    # 将路由中的英文section转换为中文
    chinese_section = SECTION_MAP.get(section)
    if not chinese_section:
        return response_error(f"不支持的section: {section}")

    # 调用服务层函数获取数据
    result = get_kr36_hotspot_from_db(chinese_section)
    result = [hotspot.to_dict() for hotspot in result]
    return response_success(result)

@kr36_bp.route("/<section>/page", methods=["GET"])
def get_kr36_hotspot_page(section):
    """
    获取36氪数据（分页）

    测试地址：
    - http://127.0.0.1:5000/kr36/flash/page?page=1&page_size=10
    - http://127.0.0.1:5000/kr36/latest/page?page=1&page_size=10
    - http://127.0.0.1:5000/kr36/zonghe/page?page=1&page_size=10
    - http://127.0.0.1:5000/kr36/hot/page?page=1&page_size=10
    - http://127.0.0.1:5000/kr36/bookmark/page?page=1&page_size=10
    """
    # 将路由中的英文section转换为中文
    chinese_section = SECTION_MAP.get(section)
    if not chinese_section:
        return response_error(f"不支持的section: {section}")

    # 获取请求参数
    page = int(request.args.get("page", 1))
    page_size = int(request.args.get("page_size", 10))
    if is_page_out_of_bounds(page, page_size):
        return response_error("page 或 page_size 不合理")

    # 调用服务层函数获取数据
    result = get_kr36_hotspot_from_db_page(chinese_section, page, page_size)
    hotspots = [hotspot.to_dict() for hotspot in result["items"]]
    result["items"] = hotspots
    return response_success(result)